package com.wyh.controller.g3controller;

import com.wyh.common.result.Result;
import com.wyh.domain.po.g3po.CollectionVerification;
import com.wyh.domain.vo.g3vo.FloorCollection;
import com.wyh.service.g3service.ArrearsService;
import com.wyh.service.g3service.FloorCollectionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

@Api(tags = "应收统计表")
@RestController
@RequestMapping("/FloorCollection")
public class FloorCollectionController {

    @Autowired
    private FloorCollectionService floorCollectionService;
    @Autowired
    private ArrearsService arrearsService;

    @ApiOperation("查找客户")
    @GetMapping("/findcustomername")
    public Result<List<Map<String, Object>>> findcustomername() {
        List<CollectionVerification> collectionVerifications = arrearsService.findcustomername();

        Set<String> customerNameSet = new HashSet<>();
        List<Map<String, Object>> result = new ArrayList<>();

        for (CollectionVerification collectionVerification : collectionVerifications) {
            String customerName = collectionVerification.getCustomername();
            if (!customerNameSet.contains(customerName)) {
                Map<String, Object> customerMap = new HashMap<>();
                customerMap.put("customerName", customerName);
                result.add(customerMap);
                customerNameSet.add(customerName);
            }
        }

        return Result.success(result);
    }
    @ApiOperation("楼盘应收统计表")
    @PostMapping("/FloorReceivable")
    public Result<List<FloorCollection>> FloorReceivable(@RequestBody Map<String, Object> request) {
        List<String> propertyNames = (List<String>) request.get("propertyNames");
        String fromBilling = (String) request.get("fromBilling");
        String endOfBilling = (String) request.get("endOfBilling");

        List<FloorCollection> matchingDetails = new ArrayList<>();
        for (String propertyName : propertyNames) {
            List<FloorCollection> details = floorCollectionService.FloorReceivable(propertyName, fromBilling, endOfBilling);
            matchingDetails.addAll(details);
        }

        for (FloorCollection floorCollection : matchingDetails) {
            // 计算逻辑
            String verificationAmount = floorCollection.getVerificationAmount();
            String accountsReceivable = floorCollection.getAccountsReceivable();
            double verificationAmountValue = Double.parseDouble(verificationAmount);
            double accountsReceivableValue = Double.parseDouble(accountsReceivable);
            double arrearsAmount = accountsReceivableValue - verificationAmountValue;
            double collectionRate = (verificationAmountValue / accountsReceivableValue) * 100.0;
            // 设置计算结果到对象中
            floorCollection.setArrearsAmount(String.valueOf(arrearsAmount));
            floorCollection.setCollectionRate(String.valueOf(collectionRate));
        }

        return Result.success(matchingDetails);
    }

    @ApiOperation("客户应收统计表")
    @PostMapping("/filterArrearsSummary")
    public Result<List<FloorCollection>> filterArrearsSummary(@RequestBody Map<String, Object> request) {
        List<String> propertyNames = (List<String>) request.get("propertyNames");
        String customerName = (String) request.get("customerName");
        String fromBilling = (String) request.get("fromBilling");
        String endOfBilling = (String) request.get("endOfBilling");

        List<FloorCollection> filteredResult = new ArrayList<>(); // 创建一个新的 List 存储筛选结果

        List<FloorCollection> matchingDetails = new ArrayList<>();
        for (String propertyName : propertyNames) {
            List<FloorCollection> details = floorCollectionService.FloorReceivable(propertyName, fromBilling, endOfBilling);
            matchingDetails.addAll(details);
        }

        for (FloorCollection floorCollection : matchingDetails) {
            // 计算逻辑
            String verificationAmount = floorCollection.getVerificationAmount();
            String accountsReceivable = floorCollection.getAccountsReceivable();
            double verificationAmountValue = Double.parseDouble(verificationAmount);
            double accountsReceivableValue = Double.parseDouble(accountsReceivable);
            double arrearsAmount = accountsReceivableValue - verificationAmountValue;
            double collectionRate = (verificationAmountValue / accountsReceivableValue) * 100.0;
            // 设置计算结果到对象中
            floorCollection.setArrearsAmount(String.valueOf(arrearsAmount));
            floorCollection.setCollectionRate(String.valueOf(collectionRate));

            String buildingCustomerName = floorCollection.getCustomerName();

            if (buildingCustomerName != null && buildingCustomerName.equals(customerName)) {
                filteredResult.add(floorCollection);
            }
        }

        return Result.success(filteredResult);
    }
    @ApiOperation("楼盘应收统计表分页")
    @PostMapping("/page")
    public Result<Map<String, Object>> page(@RequestBody Map<String, Object> request) {
        List<String> propertyNames = (List<String>) request.get("propertyNames");
        String fromBilling = (String) request.get("fromBilling");
        String endOfBilling = (String) request.get("endOfBilling");
        int currentPage = Integer.parseInt((String) request.get("currentPage"));
        int pageSize = Integer.parseInt((String) request.get("pageSize"));

        List<FloorCollection> matchingDetails = new ArrayList<>();
        for (int i = 0; i < propertyNames.size(); i++) {
            String propertyName = propertyNames.get(i);

            List<FloorCollection> details = floorCollectionService.FloorReceivable(propertyName, fromBilling, endOfBilling);
            matchingDetails.addAll(details);
        }

        // 分页处理
        int startIndex = (currentPage - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, matchingDetails.size());
        List<FloorCollection> paginatedDetails = matchingDetails.subList(startIndex, endIndex);

        for (FloorCollection floorCollection : paginatedDetails) {
            // 计算逻辑
            String verificationAmount = floorCollection.getVerificationAmount();
            String accountsReceivable = floorCollection.getAccountsReceivable();
            double verificationAmountValue = Double.parseDouble(verificationAmount);
            double accountsReceivableValue = Double.parseDouble(accountsReceivable);
            double arrearsAmount = accountsReceivableValue - verificationAmountValue;
            double collectionRate = (verificationAmountValue / accountsReceivableValue) * 100.0;
            // 设置计算结果到对象中
            floorCollection.setArrearsAmount(String.valueOf(arrearsAmount));
            floorCollection.setCollectionRate(String.valueOf(collectionRate));
        }

        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("total", matchingDetails.size());
        resultMap.put("data", paginatedDetails);

        return Result.success(resultMap);
    }

    @ApiOperation("客户应收统计表分页")
    @PostMapping("/page2")
    public Result<Map<String, Object>> page2(@RequestBody Map<String, Object> request) {
        List<String> propertyNames = (List<String>) request.get("propertyNames");
        String customerName = (String) request.get("customerName");
        String fromBilling = (String) request.get("fromBilling");
        String endOfBilling = (String) request.get("endOfBilling");
        int currentPage = Integer.parseInt((String) request.get("currentPage"));
        int pageSize = Integer.parseInt((String) request.get("pageSize"));
        List<FloorCollection> filteredResult = new ArrayList<>(); // 创建一个新的 List 存储筛选结果

        List<FloorCollection> matchingDetails = new ArrayList<>();
        for (String propertyName : propertyNames) {
            List<FloorCollection> details = floorCollectionService.FloorReceivable(propertyName, fromBilling, endOfBilling);
            matchingDetails.addAll(details);
        }

        for (FloorCollection floorCollection : matchingDetails) {
            // 计算逻辑
            String verificationAmount = floorCollection.getVerificationAmount();
            String accountsReceivable = floorCollection.getAccountsReceivable();
            double verificationAmountValue = Double.parseDouble(verificationAmount);
            double accountsReceivableValue = Double.parseDouble(accountsReceivable);
            double arrearsAmount = accountsReceivableValue - verificationAmountValue;
            double collectionRate = (verificationAmountValue / accountsReceivableValue) * 100.0;
            // 设置计算结果到对象中
            floorCollection.setArrearsAmount(String.valueOf(arrearsAmount));
            floorCollection.setCollectionRate(String.valueOf(collectionRate));
            String buildingCustomerName = floorCollection.getCustomerName();

            if (buildingCustomerName != null && buildingCustomerName.equals(customerName)) {
                filteredResult.add(floorCollection);
            }
        }

        // 分页处理
        int startIndex = (currentPage - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, filteredResult.size());
        List<FloorCollection> paginatedDetails = filteredResult.subList(startIndex, endIndex);

        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("total", filteredResult.size());
        resultMap.put("data", paginatedDetails);

        return Result.success(resultMap);
    }


    @ApiOperation("excel导出（楼盘应收统计表）")
    @PostMapping("/exportFloor")
    public Result<String> exportFloor(@RequestBody Map<String, Object> request, HttpServletResponse response) throws IOException {
        Result<List<FloorCollection>> result = FloorReceivable(request);
        List<FloorCollection> matchingDetails = result.getData();
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("楼盘应收统计表");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("楼盘名称");
        headerRow.createCell(1).setCellValue("核销金额");
        headerRow.createCell(2).setCellValue("应收金额");
        headerRow.createCell(3).setCellValue("欠款金额");
        headerRow.createCell(4).setCellValue("收缴率");

        // 填充数据
        int rowNum = 1;
        for (FloorCollection floorCollection : matchingDetails) {

            String verificationAmount = floorCollection.getVerificationAmount();
            String accountsReceivable = floorCollection.getAccountsReceivable();
            double verificationAmountValue = Double.parseDouble(verificationAmount);
            double accountsReceivableValue = Double.parseDouble(accountsReceivable);
            double arrearsAmount = accountsReceivableValue - verificationAmountValue;
            double collectionRate = (verificationAmountValue / accountsReceivableValue) * 100.0;

            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(floorCollection.getPropertyName());
            row.createCell(1).setCellValue(Double.parseDouble(floorCollection.getVerificationAmount()));
            row.createCell(2).setCellValue(Double.parseDouble(floorCollection.getAccountsReceivable()));
            row.createCell(3).setCellValue(arrearsAmount);
            row.createCell(4).setCellValue(collectionRate);

        }
        // 写入Excel文件到桌面路径
        String desktopPath = System.getProperty("user.home") + "/Desktop/楼盘应收统计表.xlsx";
        FileOutputStream fileOut = new FileOutputStream(desktopPath);
        workbook.write(fileOut);
        fileOut.close();
        return Result.success("Excel导出成功，文件路径：" + desktopPath);
    }

    @ApiOperation("excel导出（客户应收统计表）")
    @PostMapping("/exportClient")
    public Result<String> exportClient(@RequestBody Map<String, Object> request, HttpServletResponse response) throws IOException {
        Result<List<FloorCollection>> result = filterArrearsSummary(request);
        List<FloorCollection> matchingDetails = result.getData();
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("客户应收统计表");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("楼盘名称");
        headerRow.createCell(1).setCellValue("客户名称");
        headerRow.createCell(2).setCellValue("核销金额");
        headerRow.createCell(3).setCellValue("应收金额");
        headerRow.createCell(4).setCellValue("欠款金额");
        headerRow.createCell(5).setCellValue("收缴率");

        // 填充数据
        int rowNum = 1;
        for (FloorCollection floorCollection : matchingDetails) {
            String verificationAmount = floorCollection.getVerificationAmount();
            String accountsReceivable = floorCollection.getAccountsReceivable();
            double verificationAmountValue = Double.parseDouble(verificationAmount);
            double accountsReceivableValue = Double.parseDouble(accountsReceivable);
            double arrearsAmount = accountsReceivableValue - verificationAmountValue;
            double collectionRate = (verificationAmountValue / accountsReceivableValue) * 100.0;

            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(floorCollection.getPropertyName());
            row.createCell(1).setCellValue(floorCollection.getCustomerName());
            row.createCell(2).setCellValue(verificationAmountValue);
            row.createCell(3).setCellValue(accountsReceivableValue);
            row.createCell(4).setCellValue(arrearsAmount);
            row.createCell(5).setCellValue(collectionRate);
        }

        // 写入Excel文件到桌面路径
        String desktopPath = System.getProperty("user.home") + "/Desktop/客户应收统计表.xlsx";
        FileOutputStream fileOut = new FileOutputStream(desktopPath);
        workbook.write(fileOut);
        fileOut.close();
        return Result.success("Excel导出成功，文件路径：" + desktopPath);
    }

}
